<template>
    <div class="container">
        <!--        <button @click="refresh">shuaxin1111</button>-->
        <el-input placeholder="请输入病床号并回车呼叫！" v-model.trim="no"
                  style="margin-bottom: 1em; width: 20em" ref="input" :clearable="true"
                  @keyup.enter='call(no)'/>
        <el-row class="margin-bottom">
			<el-col :span="4" v-for="patient in patientData">
				<el-card class="box-card" body-style="height: 3vh" @click="call(patient.queNumber)">
					<template #header>
						<div class="card-header">
							<el-tag>{{ patient.queNumber }}床 - {{ patient.room }}房</el-tag>
							<span>{{ patient.name }}</span>
						</div>
					</template>
					<div class="text center-align margin-bottom" v-if="patient.name !== null">{{ patient.age }}岁 | {{ patient.gender }} | {{
							patient.day
						}}天
					</div>
				</el-card>
			</el-col>
        
        </el-row>

        <!-- 呼叫弹窗 -->
        <div v-if="nurseCallVisible">
            <el-dialog v-model="nurseCallVisible" width="60%"
                       :destroy-on-close="true"
                       :close-on-click-modal="false"
                       :show-close="false"
					   @close="hangup"
                       :title="'与病人通话：'+ no" center>
                <Call></Call>
                <div style="text-align: center;">
                    <el-button type="primary" :loading="true" plain>音/视频通话中...{{ timeData }}</el-button>
                    <el-button type="danger" @click="hangup()" :disabled="hangupDisabled" plain>挂断</el-button>
                    <!-- <div class="timeCount">
                        <span>{{timeData}}</span>
                    </div> -->
                </div>
            </el-dialog>
        </div>
    </div>
</template>

<script>
import {ref, reactive, computed} from "vue";
import Call from "../components/Call.vue";
import {ElMessage} from "element-plus";
import FloatList from "./FloatList.vue";
import {deviceId} from "../utils/websocket";
import {callRecord, findByQno, online, signal} from "../api/call";
import {useStore} from "vuex";
import {useRouter} from "vue-router";

export default {
    name: "CallPatient",
    components: {Call},
    mounted() {
        this.$refs.input.focus();
    },
    setup() {
        const store = useStore()
        const router = useRouter()
        const patientData = computed(() => store.state.patientData)
        //初始化窗口状态
        //const callVisible = ref(false);
        let nurseCallVisible = computed(() => store.state.nurseCallVisible)
        //禁用挂断按钮
        const hangupDisabled = ref(true);
        //呼叫的用户
        const no = ref(null);
        let socket;
        //TODO CHJ save callRecord related params
        const callRecordParams = reactive({
            startTime: "",
            endTime: "",
            callName: "",
            calledName: "",
            callId: "",
            calledId: "",
            status: "",
        })
        //TODO chj 通话弹窗计时显示
        let timeData = ref("");
        let timer = null;
        const timeCount = () => {
            // 会议计时
            let tempTime = 0;
            let second = 0;
            let minute = 0;
            let hour = 0;
            // console.log("计时器启动111-----------------------")
            timer = setInterval(() => {
                tempTime += 1;
                hour = parseInt(tempTime / 3600); // 转小时
                minute = parseInt(tempTime % 3600 / 60); // 转分钟
                second = parseInt(tempTime % 3600 % 60); // 转秒
                // 格式化
                hour = (hour > 9 ? hour : "0" + hour) + "";
                minute = (minute > 9 ? minute : "0" + minute) + "";
                second = (second > 9 ? second : "0" + second) + "";
                timeData.value = hour + ":" + minute + ":" + second;
                // console.log("计时器启动222-----------------------",timeData.value)
            }, 1000);
        }

        //定义呼叫操作
        const call = async (id) => {
            no.value = id;
            let to = null;
            for (const patient of patientData.value) {
                if (patient.queNumber === id) {
                    to = patient.deviceId;
                    //chj callRecord and time_meter相关
                    callRecordParams.calledName = patient.name
                    break;
                }
            }

            const callList = eval('(' + sessionStorage.getItem('callList') + ')');
            for (let call of callList) {
                if (call.no === id) {
                    ElMessage.info('该病床正在呼叫中，请从队列中接听');
                    return;
                }
            }
            if (to == null) {
                ElMessage.info('抱歉，该设备暂未进行初始化，请联系管理员！');
                return;
            }

            //判断是否在线，不在线直接函数结束
            let isOnline = false;
            await online(to).then((res) => {
				 isOnline = res.data
            })
            if (!isOnline) {
                ElMessage.error('对方设备不在线，请前往检查！');
                return;
            }

            //socket = FloatList.setup().socket;
            //callVisible.value = true;
            store.state.nurseCallVisible = true;

            FloatList.setup().startHandle()
              .then(() => {
                  store.state.ws.send(JSON.stringify({
                      'type': 'ask',
                      'message': {
                          'userId': deviceId,
                          'toUserId': to.toString()
                      }
                  }))
              });

            callRecordParams.startTime = Math.floor(new Date().getTime() / 1000) * 1000
            // console.log("系统时间---------------》",callRecordParams.startTime)
            callRecordParams.callId = deviceId
            callRecordParams.calledId = to.toString()
            callRecordParams.callName = "护士站"

            // console.log("计时器启动-----------------------")
            timeCount()

            //3s后允许挂断
            setTimeout(() => {
                hangupDisabled.value = false;
            }, 4000);
        };
        const hangup = () => {
            //callVisible.value = false;
            //nurseCallVisible.value=false;
            store.state.nurseCallVisible = false;

            let to;
            for (const patient of patientData.value) {
                if (patient.queNumber === no.value) {
                    to = patient.deviceId;
                    break;
                }
            }

            //chj callRecord and time_meter相关
            callRecordParams.endTime = Math.floor(new Date().getTime() / 1000) * 1000
            callRecordParams.status = "已挂断"
            callRecord(callRecordParams).then((res) => {
            })
            clearInterval(timer)
            // console.log("清除计时器-----------------")

            //TODO: 请求信号接口：挂断
			const qno = no.value;
			const p = findByQno(qno);
			if (p === null) return
			signal(p.bedId, false, 'call');

            store.state.ws.send(JSON.stringify({
                'type': 'hangup',
                'message': {
                    'userId': deviceId,
                    'toUserId': to.toString()
                }
            }));
            //刷新页面强制更新icecandidate
            // location.reload();
            refresh()
        }

        function refresh() {
            router.replace('/refresh')
        }

        return {
            //callVisible,
            nurseCallVisible,
            hangupDisabled,
            call,
            hangup,
            no,
            timeData,
            timeCount,
            patientData,
            refresh
        }
    }
}
</script>

<style scoped>
.margin-bottom {
    margin-bottom: 10px;
}

.box-card {
    min-width: 15%;
    margin-right: 10px;
    margin-bottom: 10px;
}

.box-card:hover {
    margin-top: -5px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.text {
    font-size: 10px;
}

.center-align {
    text-align: center;
}

/* .timeCount {
    margin-top: 10px;
    font-size: 10px;
} */

</style>